package cmd

import (
	"Ahq/Models"
	"Ahq/Router"
	"Ahq/Services"
	"Ahq/ValiEngine"
	_ "Ahq/ValiEngine/plugin"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/gookit/gcli/v2"
)

func createTestPaper() Models.Paper {
	var formulaConfig Services.FormulaConfig
	formulaConfig.Length = 2
	formulaConfig.SymbolTypes = []byte("+-")
	formulaConfig.Digit = 2

	var PaperConfig Services.PaperConfig
	PaperConfig.Title = "百题斩"
	PaperConfig.SubTitle = "姓名：_________日期：_________用时：______得分：___"
	PaperConfig.FormulaConfig = formulaConfig
	PaperConfig.Size = 100
	PaperConfig.Rules = strings.Split("DivisorNotBeZero,PositiveCalculation,IntegerCalculation", ",")
	return Services.GeneratePaper(&PaperConfig)
}

var Test = &gcli.Command{
	Name:   "test",
	UseFor: "测试输出试题",
	Config: func(c *gcli.Command) {
	},
	Func: func(c *gcli.Command, args []string) error {
		fmt.Println(createTestPaper())
		return nil
	},
}

var Vali = &gcli.Command{
	Name:   "vali",
	UseFor: "测试公式验证",
	Config: func(c *gcli.Command) {
	},
	Func: func(c *gcli.Command, args []string) error {
		exp := "0*1"
		rules := ValiEngine.GetCalcRulesByName(strings.Split("DivisorNotBeZero,PositiveCalculation", ","))
		fmt.Println(exp, ValiEngine.Vali(exp, rules...))
		// fmt.Printf("%#v", ValiEngine.GetAllRuleJson())
		return nil
	},
}

var Start = &gcli.Command{
	Name:   "start",
	UseFor: "启动服务",
	Config: func(c *gcli.Command) {
	},
	Func: func(c *gcli.Command, args []string) error {
		Router.InitRouter(":8080")
		return nil
	},
}

var Start80 = &gcli.Command{
	Name:   "start80",
	UseFor: "启动服务",
	Config: func(c *gcli.Command) {
	},
	Func: func(c *gcli.Command, args []string) error {
		Router.InitRouter(":80")
		return nil
	},
}

var Pdf = &gcli.Command{
	Name:   "pdf",
	UseFor: "测试生成PDF",
	Config: func(c *gcli.Command) {
	},
	Func: func(c *gcli.Command, args []string) error {
		dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(dir)

		file, _ := os.Create(fmt.Sprint(time.Now().UnixNano(), ".pdf"))
		filebyte, err := Services.Pdf(createTestPaper())
		filebyte.WriteTo(file)
		return nil
	},
}

func Command() {
	app := gcli.NewApp()
	app.Version = "0.0.1 alpha"
	app.Name = "100Questions"
	app.Logo = gcli.Logo{Text: "100Qustions", Style: "info"}
	app.Description = "百题斩"
	app.Add(Test)
	app.Add(Vali)
	app.Add(Start)
	app.Add(Start80)
	app.Add(Pdf)
	app.Run()
}
